﻿##include texas / config / dbInc.as
/**
 * 實例化mysql連接
 * @param	name	數據庫標識
 */
function loadDB(dbName) {
	var _mysql = new mysql();	
	var _db_config;
	//_db_config = SFS_DEBUG_MODEL ? configDB[0] : configDB[1];
	_db_config = DBCONFIG[dbName];
	_mysql._host		= _db_config.host;
	_mysql._user		= _db_config.user;
	_mysql._pass		= _db_config.pass;
	_mysql._database	= _db_config.name;
	_mysql._zoneName 	= _db_config.name;
	_mysql.init();
	return _mysql;
}
/**
 * mysql連接類
 * 
 */
function mysql() {
	/**
	 * 數據庫鏈接擴展配置
	 */
	this._host 		= "";
	this._port		= "3306";
	this._database 	= "texas";
	this._user		= "fog_admin";
	this._pass		= "flash";
	this._zoneName 	= "texas";
	/**
	 * sfs配置
	 */
	var _driverName = "org.gjt.mm.mysql.Driver";
	var _connString = "jdbc:mysql://";
	var maxActive 	= 1000;
	var maxIdle 	= 1000;
	var exhaustedAction = "fail";
	var blockTime 	= 5000;
	

	/**
	 * 連接類變量
	 */	
	var _query_id	= "";
	var _sql		= "";
	var _result		= new Object();
	//this._db = null;

	/**
	 * 建立數據庫鏈接
	 */
	if(this.init==null){
	this.init = function() {
		if ( this._db == null ) {			
			_connString += this._host + ":" + this._port +"/" + this._database +"?useUnicode=true&characterEncoding=utf8";
			this._db = new __db.DbManager(_driverName, _connString, this._user, this._pass, this._zoneName, maxActive, maxIdle, exhaustedAction, blockTime);			
		}		
	}	
	}
	/**
	 * 執行sql語句並返回結果集
	 */
	this.query = function(r_sql, r_arg) {
		if(this.replace(r_sql, r_arg)){
			r_sql = this.replace(r_sql, r_arg);		
		}
		//_sql = _server.escapeQuotes(r_sql);
		_result = this._db.executeQuery(r_sql);
		_result = (_result.size() == 0) ? null :_result;
		return _result;
	}
	
	/**
	 * @return blooean true為執行成功
	 */
	this.execute = function(r_sql, r_arg) {	
		if(this.replace(r_sql, r_arg)){
			r_sql = this.replace(r_sql, r_arg);		
		}
		var _res = this._db.executeCommand(r_sql);		
		if(!_res){
			if (__log) {
				__log.write("sql", r_sql);
			}
		}
		return _res;
	}
	
	/**
	 * 查詢一條記錄
	 */
	this.selectOne = function(_sql) {				
		//this.init();
		//_sql = _server.escapeQuotes(r_sql);	
		_result = this._db.executeQuery(_sql);			
		if ( _result.size() == 0) {
			_result = null;
		}else {
			_result = _result.get(0);
		}
		if(!_result){
			if (__log) {
				__log.write("sql", _sql);
			}
		}
		return _result;
	}	
}

mysql.prototype.replace = function(r_sql, r_arg) {
	if (!r_arg || r_arg.length <= 0 ) {
		return r_sql;
	}
	var _macth = r_sql.match(/(%[sd])|(\'%[sd]\'){1}/gi);
	var _len = _macth.length;
	for (var i = 0; i < _len; i++ ) {
		var _val = r_arg[i];		
		var _mac = _macth[i];
		if (_mac == "%s" || _mac == "'%s'") {
			_val = "'" + _server.escapeQuotes(_val) + "'";
		}				
		var _rep = r_sql.replace(_mac, _val);
		r_sql = _rep;			
	}
	return r_sql;
}